<?php

namespace App\Http\Controllers\Admin;

use App\Constants\AppConstants;
use App\Http\Controllers\Controller;
use App\Models\AdminLog;
use Illuminate\Http\Request;
use Inertia\Inertia;
use Inertia\Response;

class AdminLogController extends Controller
{
    /**
     * 显示日志列表
     */
    public function index(Request $request): Response
    {
        $query = AdminLog::with('user')
            ->orderBy('created_at', 'desc');

        // 筛选条件
        if ($request->filled('action')) {
            $query->where('action', $request->action);
        }

        if ($request->filled('module')) {
            $query->where('module', $request->module);
        }

        if ($request->filled('user_id')) {
            $query->where('user_id', $request->user_id);
        }

        if ($request->filled('date_from')) {
            $query->whereDate('created_at', '>=', $request->date_from);
        }

        if ($request->filled('date_to')) {
            $query->whereDate('created_at', '<=', $request->date_to);
        }

        if ($request->filled('search')) {
            $query->where('description', 'like', '%' . $request->search . '%');
        }

        $logs = $query->paginate(AppConstants::PAGINATION_LOG_DEFAULT)->withQueryString();

        // 统计数据
        $stats = [
            'total' => AdminLog::count(),
            'today' => AdminLog::whereDate('created_at', today())->count(),
            'this_week' => AdminLog::whereBetween('created_at', [now()->startOfWeek(), now()->endOfWeek()])->count(),
            'this_month' => AdminLog::whereMonth('created_at', now()->month)->count(),
        ];

        // 操作类型统计
        $actionStats = AdminLog::selectRaw('action, COUNT(*) as count')
            ->groupBy('action')
            ->get()
            ->mapWithKeys(fn($item) => [$item->action => $item->count]);

        // 模块统计
        $moduleStats = AdminLog::selectRaw('module, COUNT(*) as count')
            ->groupBy('module')
            ->get()
            ->mapWithKeys(fn($item) => [$item->module => $item->count]);

        return Inertia::render('Admin/Logs/Index', [
            'logs' => $logs,
            'stats' => $stats,
            'actionStats' => $actionStats,
            'moduleStats' => $moduleStats,
            'filters' => $request->only(['action', 'module', 'user_id', 'date_from', 'date_to', 'search']),
        ]);
    }

    /**
     * 显示日志详情
     */
    public function show(AdminLog $log): Response
    {
        $log->load('user');

        return Inertia::render('Admin/Logs/Show', [
            'log' => $log,
        ]);
    }

    /**
     * 清理旧日志
     */
    public function cleanup(Request $request)
    {
        $request->validate([
            'days' => 'required|integer|min:1|max:365',
        ]);

        $date = now()->subDays($request->days);
        $deleted = AdminLog::where('created_at', '<', $date)->delete();

        return back()->with('success', "已删除 {$deleted} 条旧日志记录");
    }
}
